package dxunderground.utilities.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread implements Runnable {
	private Socket socket = null;

	public ServerThread(Socket socket) {
		this.socket = socket;
		System.out.println("Connection from: " + socket.getInetAddress());
	}

	public void run() {
		try {
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			// out.println("Connection Established.");

			String inputLine, outputLine;
			Protocol protocol = new Protocol();

			while ((inputLine = in.readLine()) != null) {
				outputLine = protocol.processInput(inputLine);
				out.println(outputLine);
				if (outputLine.equals("__END__")) {
					break;
				}
			}
			out.close();
			in.close();
			socket.close();
			System.out.println("Closed connection from: " + socket.getInetAddress());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}